package cn.ug.activity.mq;

import cn.ug.activity.mapper.entity.CouponMember;
import cn.ug.activity.service.CouponMemberService;
import cn.ug.bean.base.SerializeObject;
import cn.ug.bean.type.ResultType;
import cn.ug.config.RedisGlobalLock;
import cn.ug.core.SerializeObjectError;
import cn.ug.enums.WxTemplateEnum;
import cn.ug.feign.MemberAccountService;
import cn.ug.feign.MemberUserService;
import cn.ug.feign.ProductOrderService;
import cn.ug.msg.mq.Msg;
import cn.ug.msg.mq.WxMessageParamBean;
import cn.ug.msg.mq.WxNotifyData;
import cn.ug.pay.bean.ProductOrderBean;
import cn.ug.pay.bean.response.MemberAccountBean;
import cn.ug.pay.bean.type.TradeType;
import cn.ug.util.BigDecimalUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static cn.ug.config.QueueName.*;
import static cn.ug.util.RedisConstantUtil.DONATION_CASH_ERROR_KEY;

@Component
@RabbitListener(queues = QUEUE_COUPON_DONATION_CASH)
public class DonationCashReceiver {
    private Log log = LogFactory.getLog(DonationCashReceiver.class);
    private ObjectMapper mapper = new ObjectMapper();
    @Autowired
    private CouponMemberService couponMemberService;
    @Autowired
    private MemberUserService memberUserService;
    @Autowired
    private MemberAccountService memberAccountService;
    @Autowired
    private RedisGlobalLock redisGlobalLock;
    @Autowired
    private AmqpTemplate amqpTemplate;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private ProductOrderService productOrderService;
    @RabbitHandler
    public void process(DonationCashMQ o) throws JsonProcessingException {
        log.info("DonationCashReceiver:process.......................");
        /*if (o == null || StringUtils.isBlank(o.getCouponId()) || o.getCouponAmount() == null) {
            return;
        }
        try {
            Thread.sleep(90000);
        } catch (Exception e) {

        }
        String key = DONATION_CASH_ERROR_KEY + o.getCouponId();
        String value = redisTemplate.opsForValue().get(key);
        if (StringUtils.isNotBlank(value)) {
            int num = Integer.parseInt(value);
            if (num > 15) {
                return;
            }
        }

        String numValue = redisTemplate.opsForValue().get(key);
        if (StringUtils.isNotBlank(numValue)) {
            int num = Integer.parseInt(numValue);
            num++;
            redisTemplate.opsForValue().set(key, String.valueOf(num), 3600, TimeUnit.SECONDS);
        } else {
            redisTemplate.opsForValue().set(key, String.valueOf(1), 3600, TimeUnit.SECONDS);
        }
        log.info(mapper.writeValueAsString(o));
        String lockKey = "DonationCashReceiver:process:couponId:" + o.getCouponId();
        try {
            if(!redisGlobalLock.lock(lockKey, 1, TimeUnit.HOURS)) {
                throw new RuntimeException("优惠券转现金获取锁失败.");
            }
            CouponMember couponMember = couponMemberService.get(o.getCouponId());
            if (couponMember == null || couponMember.getCoupon() == null || StringUtils.isBlank(couponMember.getMemberId())) {
                log.error(new SerializeObjectError("22000004").getMsg());
                return;
            }
            if (couponMember.getGrantStatus() == 2) {
                log.error(new SerializeObjectError("22000017").getMsg());
                return;
            }
            SerializeObject<ProductOrderBean> productOrderBeanSerializeObject = productOrderService.findByOrderId(couponMember.getOrderId());
            if (couponMember.getCoupon().getType() == 3) {
                SerializeObject bean = memberAccountService.inviteReturnCash(couponMember.getMemberId(), o.getCouponAmount(), TradeType.RATE_INCREASE.getValue());
                if(bean == null || bean.getCode() != ResultType.NORMAL) {
                    if (bean != null) {
                        log.error("福利券转化为现金错误：code:"+bean.getCode()+",msg:"+bean.getMsg());
                    }
                    throw new RuntimeException("福利券转化为现金错误");
                }
                Msg rechargeMsg = new Msg();
                rechargeMsg.setMemberId(couponMember.getMemberId());
                rechargeMsg.setType(cn.ug.msg.bean.status.CommonConstants.MsgType.TICKET_CASH.getIndex());
                Map<String, String> rechargeParamMap = new HashMap<>();
                rechargeParamMap.put("productName", o.getProductName());
                rechargeParamMap.put("money", String.valueOf(o.getCouponAmount().doubleValue()));
                rechargeMsg.setParamMap(rechargeParamMap);
                amqpTemplate.convertAndSend(QUEUE_MSG_SEND, rechargeMsg);

                sendWx(couponMember.getMemberId(),String.valueOf(o.getCouponAmount().doubleValue()),
                        cn.ug.msg.bean.status.CommonConstants.MsgType.TICKET_CASH.getName(),productOrderBeanSerializeObject.getData().getAddTimeString(),couponMember.getOrderId());
            } else {
                SerializeObject bean = memberAccountService.inviteReturnCash(couponMember.getMemberId(), o.getCouponAmount(), TradeType.CASH_BACK.getValue());
                if(bean == null || bean.getCode() != ResultType.NORMAL) {
                    if (bean != null) {
                        log.error("现金红包转化为现金错误：code:"+bean.getCode()+",msg:"+bean.getMsg());
                    }
                    throw new RuntimeException("现金红包转化为现金错误");
                }
                Msg rechargeMsg = new Msg();
                rechargeMsg.setMemberId(couponMember.getMemberId());
                rechargeMsg.setType(cn.ug.msg.bean.status.CommonConstants.MsgType.COUPON_CASH.getIndex());
                Map<String, String> rechargeParamMap = new HashMap<>();
                rechargeParamMap.put("productName", o.getProductName());
                rechargeParamMap.put("money", String.valueOf(o.getCouponAmount().doubleValue()));
                rechargeMsg.setParamMap(rechargeParamMap);
                amqpTemplate.convertAndSend(QUEUE_MSG_SEND, rechargeMsg);

                sendWx(couponMember.getMemberId(),BigDecimalUtil.to2Point(o.getCouponAmount()).toString(),
                        cn.ug.msg.bean.status.CommonConstants.MsgType.COUPON_CASH.getName(),productOrderBeanSerializeObject.getData().getAddTimeString(),couponMember.getOrderNO());
            }
            *//*couponMember.setGrantAmount(o.getCouponAmount());
            couponMember.setGrantStatus(2);
            couponMember.setGrantTime(LocalDateTime.now());
            couponMember.setGrantGold(o.getGoldAmount());*//*
            couponMemberService.donate(couponMember);

        } finally {
            redisGlobalLock.unlock(lockKey);
        }
*/
    }

    /**
     * 微信消息推送
     * @param memberId
     * @param couponAmount
     */
    public void sendWx(String memberId,String couponAmount,String msgType,String orderTime,String orderId){
        SerializeObject<MemberAccountBean> memberAccount = memberAccountService.findByMemberId(memberId);
        productOrderService.findByOrderId(orderId);
        /**
         * 微信服务号消息推送  收支变动
         */
        WxMessageParamBean wxMessageParamBean = new WxMessageParamBean();
        wxMessageParamBean.setMemberId(memberId);
        wxMessageParamBean.setType(WxTemplateEnum.FUND_CHANGE.getType());
        WxTemplateEnum wxTemplateEnum = WxTemplateEnum.getWxTemplateByCode(WxTemplateEnum.FUND_CHANGE.getType());
        WxNotifyData wxNotifyData = new WxNotifyData();

        Map<String,WxNotifyData.TemplateDataAttr> wxParamMap = new HashMap();
        WxNotifyData.TemplateDataAttr first = new WxNotifyData.TemplateDataAttr();
        first.setDataValue(wxTemplateEnum.getFirstData());
        wxParamMap.put("first",first);

        WxNotifyData.TemplateDataAttr keyword1 = new WxNotifyData.TemplateDataAttr();
        keyword1.setDataValue(msgType);
        wxParamMap.put("keyword1",keyword1);

        WxNotifyData.TemplateDataAttr keyword2 = new WxNotifyData.TemplateDataAttr();
        keyword2.setDataValue(couponAmount);
        wxParamMap.put("keyword2",keyword2);

        WxNotifyData.TemplateDataAttr keyword3 = new WxNotifyData.TemplateDataAttr();
        keyword3.setDataValue(orderTime);
        wxParamMap.put("keyword3",keyword3);


        WxNotifyData.TemplateDataAttr keyword4 = new WxNotifyData.TemplateDataAttr();
        keyword4.setDataValue(BigDecimalUtil.to2Point(memberAccount.getData().getUsableAmount()).toString());
        wxParamMap.put("keyword4",keyword4);

        WxNotifyData.TemplateDataAttr remark = new WxNotifyData.TemplateDataAttr();
        remark.setDataValue(wxTemplateEnum.getRemark());
        wxParamMap.put("remark",remark);

        wxNotifyData.setData(wxParamMap);
        wxMessageParamBean.setTemplateData(wxNotifyData);
        amqpTemplate.convertAndSend(QUEUE_MSG_WX_SEND, wxMessageParamBean);
    }
}
